#!/bin/env python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    Add By :e4ting e4ting@gmail.com 2023-09-24 16:33:29
"""
import sys,os
import json,time
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack
from textwrap import dedent

from flask_restful import Resource
from flask         import redirect,request,make_response

from e4ting  import log,util
from core.webhook import Robot,MessageTemp

class WebTemplates(Resource):
    ''' 消息模板管理 '''
    #----------------------------------------------------------------------
    def __init__(self):
        super(WebTemplates, self).__init__()

    def get(self, **kwargs):
        items = MessageTemp.load_all()
        data = [ _.webdumps() for _ in items]
        data.sort(key=lambda x:x.get("uptime") or "", reverse=True)
        return dict(code=200, data=data, total=len(data))

    def post(self, id=0, **kwargs):
        """
            用整数做ID，简直就是自寻死路，万一别人构造请求，批量删除，易如反掌
        """
        data = request.json
        _id = data.get("id")
        log.info(f"修改模板 {_id}")
        if not _id:
            return dict(code=400, data="修改失败")
        # _id = int(_id)
        MessageTemp.update(_id, name=data["name"], type=data["type"], text=data["text"])
        return dict(code=200, data="修改成功 : {name}".format(**data))

    def put(self, id=0, **kwargs):
        """
            用整数做ID，简直就是自寻死路，万一别人构造请求，批量删除，易如反掌
        """
        data = request.json
        MessageTemp.update(name=data["name"], type=data["type"], text=data["text"])
        return dict(code=200, data="创建成功 : {name}".format(**data))

    def delete(self, id=0, **kwargs):
        """
            用整数做ID，简直就是自寻死路，万一别人构造请求，批量删除，易如反掌
        """
        _id = id or request.args.get("id") or request.json.get("id")
        log.info(f"删除模板 {_id}")
        if not _id:
            return dict(code=400, data="删除失败")
        # _id = int(_id)
        if MessageTemp.delete(_id):
            return dict(code=200, data="删除成功")
        else:
            return dict(code=400, data="删除失败")

